package com.aidex.ajreport.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aidex.ajreport.domain.GaeaReportDashboard;
import com.aidex.ajreport.domain.GaeaReportDashboardWidget;
import com.aidex.ajreport.mapper.GaeaReportDashboardMapper;
import com.aidex.ajreport.mapper.GaeaReportDashboardWidgetMapper;
import com.aidex.ajreport.service.GaeaReportDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GaeaReportDashboardServiceImpl extends ServiceImpl<GaeaReportDashboardMapper, GaeaReportDashboard> implements GaeaReportDashboardService {
    @Autowired
    private GaeaReportDashboardWidgetMapper dashboardWidgetMapper;
    @Override
    public GaeaReportDashboard queryByRcode(String rcode) {
        return baseMapper.queryByRcode(rcode);
    }

    private void updateWidgets(String rcode, List<GaeaReportDashboardWidget> widgets) {
        UpdateWrapper<GaeaReportDashboardWidget> wrapper = new UpdateWrapper<>();
        wrapper.eq("rcode", rcode);
        dashboardWidgetMapper.delete(wrapper);
        if(widgets != null){
            for (GaeaReportDashboardWidget widget : widgets){
                widget.setRcode(rcode);
                dashboardWidgetMapper.insert(widget);
            }
        }
    }

    @Override
    @Transactional
    public boolean create(GaeaReportDashboard entity) {
        updateWidgets(entity.getRcode(), entity.getWidgets());
        return super.save(entity);
    }

    @Override
    @Transactional
    public boolean update(GaeaReportDashboard entity) {
        updateWidgets(entity.getRcode(), entity.getWidgets());
        return super.updateById(entity);
    }


}
